import Http from '@/Http'
import { getToken, setToken, removeToken } from '@/utils/auth'
const login = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_INTRODUCTION(state, introduction) {
      state.introduction = introduction
    },
    SET_NAME(state, name) {
      state.name = name
    },
    SET_AVATAR(state, avatar) {
      state.avatar = avatar
    },
    SET_ROLES(state, roles) {
      state.roles = roles
    }
  },
  actions: {
    // 登录接口 拿到token后，发送token给后台，返回信息
    Login({ commit }, { user, password }) {
      return new Promise((resolve, reject) => {
        Http.post('/login', {
          user,
          password
        }).then(response => {
          if (response) {
            const { datas } = response.data
            commit('SET_TOKEN', datas.token)
            setToken(datas.token)
            resolve(datas)
          } else {
            resolve(response)
          }
        })
      })
    },

    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    GetUserInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        Http.post('/getUserInfo')
          .then(response => {
            const { datas } = response.data
            if (datas) {
              commit('SET_INTRODUCTION', datas.introduction)
              commit('SET_NAME', datas.name)
              commit('SET_AVATAR', datas.avatar)
              commit('SET_ROLES', datas.roles)
              resolve(datas)
            } else {
              reject()
            }
          })
          .catch(() => {
            reject()
          })
      })
    }
  }
}

export default login
